package com.rttmall.shopbackend.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;

import com.alibaba.simpleimage.ImageRender;
import com.alibaba.simpleimage.SimpleImageException;
import com.alibaba.simpleimage.render.ReadRender;
import com.alibaba.simpleimage.render.ScaleParameter;
import com.alibaba.simpleimage.render.ScaleRender;
import com.alibaba.simpleimage.render.WriteRender;

/**
 * 文件操作工具类
 * 
 */
public class FileUtil {

	/**
	 * 图片压缩
	 * @param inStream
	 * @return
	 */
	public static File compressImg(InputStream inStream,String tempPath,String fileName){
		File dir = new File(tempPath);
		File temp = new File(dir,"small"+fileName);
		if(!dir.exists()){
			dir.mkdirs();
		}
        ScaleParameter scaleParam = new ScaleParameter(250, 250);  //将图像缩略到1024x1024以内，不足1024x1024则不做任何处理  
          
        OutputStream outStream = null;  
        WriteRender wr = null;  
        try {  
            outStream = new FileOutputStream(temp);  
            ImageRender rr = new ReadRender(inStream);  
            ImageRender sr = new ScaleRender(rr, scaleParam);  
            wr = new WriteRender(sr, outStream);  
            wr.render();   
            return temp;
            //触发图像处理  
        } catch(Exception e) {  
            e.printStackTrace();  
        } finally {  
            IOUtils.closeQuietly(inStream);         //图片文件输入输出流必须记得关闭  
            IOUtils.closeQuietly(outStream);  
            if (wr != null) {  
                try {  
                    wr.dispose();                   //释放simpleImage的内部资源  
                } catch (SimpleImageException ignore) {  
                    // skip ...   
                }  
            }  
        }
        return null;
	}
	/**
	 * 获取文件扩展名
	 * 
	 * @param filename
	 * @return
	 */
	public static String getExtend(String filename) {
		return getExtend(filename, "");
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @param filename
	 * @return
	 */
	public static String getExtend(String filename, String defExt) {
		if ((filename != null) && (filename.length() > 0)) {
			int i = filename.lastIndexOf('.');
			if ((i > 0) && (i < (filename.length() - 1))) {
				return (filename.substring(i + 1)).toLowerCase();
			}
		}
		return defExt.toLowerCase();
	}

}
